<template>
	<view class="pdb-32" :class="showPopup?'box_fixed':'box'">
		<view class="nav_box">
			<myNav :title="title" :height="65" :isBlack="true" title-color="#ffffff" back-icon-color="#ffffff" />
		</view>
		<image class="bg" src="/static/src/borrow/bg.png" mode="aspectFill"></image>
		<view class="borrrow_wrap pdl-30 pdr-30 mgt-64">
			<u-form :model="form" ref="formRef" :error-type="errorType" label-width="180" :label-style="formStyle">
				<view class="borrow_top">
					<view class="pdt-52">
						<view class="small_chinese mgl-70 fs28">
							<text class="small_shu pdr-10">|</text>{{moneyChinese}}
						</view>
					</view>
					<u-form-item class="pdt-10 pdb-40 mgl-28 mgr-28" prop="money" label-width="40">
						<view class="df money_input">
							<text class="money_sign fs62">￥</text>
							<u-input @input="handleChange" @blur="handleMoney" :custom-style='moneyStyle' type="number"
								v-model="form.money" :placeholder="placeholderMoney" clearable maxlength="120"
								showWordLimit />
							<view class="all_btn pdl-20 pdr-20" @click="handleAll">全部借出</view>
						</view>
					</u-form-item>
					<u-form-item class="mgl-28 mgr-28" label="借款期限" prop="loanTerm">
						<view class="df flex1 term_input flex-ac" @click="handlePeriod(1)">
							<view  class="mgr-12" :class="form.loanTerm?'':'default'">
								{{form.loanTerm?`${form.loanTerm}期`:'请选择借款期限'}}
							</view>
							<view class="df mgt-5">
								<u-icon name="arrow-right" color="#CCCCCC" size="26"></u-icon>
							</view>
						</view>
					</u-form-item>
					<u-form-item class="mgl-28 mgr-28" label="借款天数" prop="daysPerTerm">
						<view class="df flex1 term_input flex-ac">
							<view class="mgr-12" :class="form.daysPerTerm?'':'default'">
								{{form.daysPerTerm?form.daysPerTerm*form.loanTerm:'借款天数'}}
							</view>
						</view>
					</u-form-item>
					<view class="interest_box flex-ac flex-sb mgl-19 mgl-28 mgr-28">
						<view>
							利息<text class="interest_desc">(还款时收取)</text>
						</view>
						<view class="df interest_right flex-ac fs28">
							<view class="mgr-12" :class="form.daysPerTerm?'':'default'">
								年化{{annualized}}(￥{{interest}})
							</view>
						</view>
					</view>
				</view>
				<view class="credit_certificates mgt-20 pdl-33 pdr-30">
					<view class="flex-ac flex-sb pdt-30">
						<view class="title fs32">信用担保凭证</view>
						<view class="money fs36">￥{{certificatesMoney}}</view>
					</view>
					<view class="note mgt-14 pdb-28 fs22">
						本凭证作为增信作用收取且不予退还，还款时支付
					</view>
				</view>
				<view class="repayment_plan mgt-20 pdl-32 pdr-31">
					<view class="total_wrap flex-sb fs28">
						<view class="total_left">总还款金款</view>
						<view class="total_right">￥{{totalMoney}}</view>
					</view>
					<view class="repayment_wrap flex-sb fs28">
						<view class="repayment_left">还款计划</view>
						<view class="repayment_right">每30天还款</view>
					</view>
				</view>
				<view class="bottom mgt-20">
					<u-form-item class="mgl-28 mgr-28" label="借款用途" prop="borrowPurpose">
						<view class="df flex1 purpose_input flex-ac" @click="handlePeriod(2)">
							<view class="mgr-12" :class="form.borrowPurpose?'':'default'">
								{{form.borrowPurpose?form.borrowPurpose:'请选择借款用途'}}
							</view>
							<view class="df mgt-5">
								<u-icon name="arrow-right" color="#CCCCCC" size="26"></u-icon>
							</view>
						</view>
					</u-form-item>
					<u-form-item class="mgl-28 mgr-28" label="收款银行卡" prop="purpose">
						<view class="df flex1 purpose_input flex-ac">
							<view @click="handleAdd" class="add mgr-12" v-if="form.bank && form.bank.length===0">
								添加银行卡
							</view>
							<view class="u-overflow-1 mgr-12" v-else @click="handlePeriod(3)">
								{{accountOpeningBank}}
							</view>
							<view class="df mgt-5">
								<u-icon name="arrow-right" color="#CCCCCC" size="26"></u-icon>
							</view>
						</view>
					</u-form-item>
					<view class="institution_wrap flex-sb fs28 pdl-32 pdr-31">
						<view class="institution_left">放款机构</view>
						<view class="institution_right">{{lendingInstitution?lendingInstitution:'第三方合法放款机构'}}</view>
					</view>
				</view>
				<u-checkbox-group size="30" class="mgt-41 mgl-33">
					<u-checkbox v-model="checked" shape="circle">
						<view class="agreement_wrap fs24">
							我已阅读并同意
							<text class="agreement">《授权借款协议》</text>
						</view>
					</u-checkbox>
				</u-checkbox-group>
			</u-form>
			<u-button @click="handleSubmit" class="submit_btn mgt-16 fs32" shape="circle" :disabled="disabled"
				:ripple="true" throttle-time="2000">确定</u-button>
			<!-- 单列 -->
			<u-select :default-value="[getCurrentIndex]" v-model="showSelect" :safe-area-inset-bottom="true"
				mode="single-column" :list="list" label-name="label" value-name="value"
				@confirm="handConfim"></u-select>
			<!-- 借款协议 -->
			<loanPopup :showPopup="showPopup" @update="handleClose" @back="handleBack" />
			<borrowKeyBoard :showKeyBoard="showKeyBoard" />
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed } from 'vue';

	import { useInformation } from '@/store/modules/index.ts'

	import { onShow, onLoad } from "@dcloudio/uni-app";

	import { getDict } from "@/api/dict";

	import { getLoan, getPay } from "@/api/borrow"

	import type { FormData, loanItem, ListItem, bankItem } from "../../static/src/types/loan"

	import myNav from "../../components/myNav.vue"
	import loanPopup from "./components/loanPopup.vue"
	import borrowKeyBoard from "../../components/borrowKeyBoard.vue"

	const user = useInformation()

	const title = ref<string>("借款")
	const placeholderMoney = ref<string>("")
	const annualized = ref<string>("24.00")
	const interest = ref<string>("30.00")
	const certificatesMoney = ref<string>("0")
	const totalMoney = ref<string>("0")
	const checked = ref<boolean>(false)
	const disabled = ref<boolean>(false)
	const loanArr = ref<loanItem>({
		banks: [],
		interestConfigs: [],
		lendingInstitution: "",
		vouchAmount: ""
	});
	
	const interestConfigId = ref<string>("")
	const form = ref<FormData>({
		money: "",
		loanTerm: null,
		daysPerTerm: null,
		bank: [],
		borrowPurpose: "",
		borrowPurposeId: ""

	})
	const accountOpeningBank = ref<string>("")
	const bankId = ref<string>("")
	const errorType = ref(['message'])
	const showSelect = ref<boolean>(false)
	const list = ref<ListItem[]>([]);
	const currentType = ref<number>(0)
	const borrowDateIndex = ref<number>(0);
	const purposeIndex = ref<number>(0);
	const bankIndex = ref<number>(0);
	const lendingInstitution = ref<string>("")
	const showPopup = ref<boolean>(false)
	const showKeyBoard = ref<boolean>(false)
	const isShowFace = ref<boolean>(true)

	const formStyle = {
		color: '#5A5B66',
		fontFamily: ' PingFang SC',
		fontWeight: '500',
		fontSize: '28rpx'
	}
	const moneyStyle = {
		color: '#333333',
		fontSize: '85rpx',
		fontWeight: '500',
		fontFamily: 'IQYHT'
	}

	const moneyChinese = computed(() => {
		const num = parseFloat(form.value.money);
		if (isNaN(num)) return ''; // 非数字处理
		if (num >= 10000) {
			const wan = num / 10000;
			return wan % 1 === 0 ? `${wan}万` : `${wan.toFixed(1)}万`;
		}
		else if (num >= 1000) {
			const qian = num / 1000;
			return qian % 1 === 0 ? `${qian}千` : `${qian.toFixed(1)}千`;
		}
		return `${num}元`;
	})
	const getCurrentIndex = computed(() => {
		switch (currentType.value) {
			case 1:
				return borrowDateIndex.value;
			case 2:
				return purposeIndex.value;
			default:
				return 0;
		}
	})

	const getData = async () => {
		let res = await getLoan(user.phoneNumber)
		loanArr.value = res.data
		certificatesMoney.value = res.data.vouchAmount
		lendingInstitution.value = res.data.lendingInstitution
		form.value.bank = res.data.banks || []
		if(form.value.bank && res.data.banks.length>0){
			accountOpeningBank.value = `${res.data.banks[0].accountOpeningBank} ${res.data.banks[0].bankCardNumber}`
			bankId.value = res.data.banks[0].bankId
		}
		
	}
	const listData = async () => {
		list.value = loanArr.value.interestConfigs.map((item : any) => ({
			label: `${item.loanTerm}期`,
			value: item.interestConfigId
		}));
	}
	
	const bankData = async ()=>{
		list.value = loanArr.value.banks?.map((item : any) => ({
			label:`${item.accountOpeningBank} ${item.bankCardNumber}`,
			value: item.bankId
		}))?? [];	
	}

	const loadDictData = async (value : string) => {
		let res = await getDict(value)
		if (res) {
			list.value = res.data.map((item : any) => ({
				label: item.dictLabel,
				value: item.dictValue
			}));
		}
	}
	const handlePeriod = async (type : number) => {
		if (!form.value.money) {
			uni.showToast({
				icon: 'none',
				title: '请先填入借款金额'
			});
			return
		}
		currentType.value = type
		switch (currentType.value) {
			//期限
			case 1:
				await listData()
				break;
			//用途
			case 2:
				await loadDictData('lo_loan_purpose')
				break;
			//银行卡
			case 3:
				await bankData()
				break;
			default: 0
		}
		showSelect.value = true
	}
	
	const handConfim = async (e : any) => {
		//期限
		if (currentType.value === 1) {
			let arr = []
			arr = loanArr.value?.interestConfigs?.filter((item : any) => item.interestConfigId === e[0].value);
			console.log(arr[0], '选择的配置')
			interestConfigId.value = arr[0].interestConfigId
			form.value.loanTerm = arr[0].loanTerm
			form.value.daysPerTerm = arr[0].daysPerTerm
			annualized.value = arr[0].annualRate
			let res = await getPay(interestConfigId.value, form.value.money)
			if (res) {
				certificatesMoney.value = res.data.vouchAmount
				totalMoney.value = res.data.dueAmount
				interest.value = res.data.dueInterest
			}
			borrowDateIndex.value = list.value.findIndex(item => item.value === e[0].value);
		}
		//用途
		if (currentType.value === 2) {
			form.value.borrowPurpose = e[0].label
			form.value.borrowPurposeId = e[0].value
			purposeIndex.value = list.value.findIndex(item => item.value === e[0].value);
		}
		//银行卡
		if (currentType.value === 3) {
			accountOpeningBank.value = e[0].label
			bankId.value = e[0].value
			bankIndex.value = list.value.findIndex(item => item.value === e[0].value);
		}
	}
	const clearSelections = () => {
		form.value = {
			...form.value,
			loanTerm: null,
			daysPerTerm: null,
			bank: null,
			borrowPurpose: "",
			borrowPurposeId: ""
		}
		totalMoney.value = "0"
	};

	const handleMoney = (value : string) => {
		// // 1. 检查是否超过最大可借金额
		const numValue = Number(value);
		const maxValue = Number(placeholderMoney.value);
		if (numValue > maxValue) {
			uni.showToast({
				title: `输入金额不能大于${maxValue}元`,
				icon: 'none'
			});
			form.value.money = '';
			clearSelections(); // 清空选择条件
		}

		// 2. 处理小数输入
		if (value.includes('.')) {
			form.value.money = value.split('.')[0];
			clearSelections(); // 清空选择条件
		}
	}

	const handleChange = (e : string) => {
		if (e !== form.value.money) {
			clearSelections();
		}
	}
	const handleAll = () => {
		const money = uni.getStorageSync('money');
		form.value.money = parseInt(money).toString();
	}

	const formatBankerRound = (num : any) => {
		return (Math.round(num * 100) / 100).toFixed(2);
	}
	const handleAdd = () => {
		uni.navigateTo({
			url: "/pages/bank/add"
		})
	}
	const handleSubmit = () => {
		if (!checked.value) {
			uni.showToast({
				title: '请先阅读并同意授权借款协议',
				icon: 'none'
			});
			return;
		}
		showPopup.value = true
	}
	const handleBack = (v : boolean) => {
		showPopup.value = v
	}
	const handleClose = (v : boolean) => {
		showPopup.value = v
		uni.navigateTo({
			url: "/pages/face/index"
		})
	}


	onLoad(() => {
		uni.$on('getIdentify', (data : boolean) => {
			if (data) {
				showKeyBoard.value = true
			}
		})
		uni.$on('getBank', (data : boolean) => {
			if (data) {
				getData()
			}
		})
	})

	onShow(() => {
		if (uni.getStorageSync('money')) {
			const money = uni.getStorageSync('money');
			placeholderMoney.value = formatBankerRound(money);
		}
		getData()
	})
</script>

<style lang="scss" scoped>
	@import '@/style/style.scss';

	.box {
		height: 100%;
		min-height: 100vh;
		position: relative;
		background: #F5F5F6;
		z-index: 10;

		.nav_box {
			z-index: 100;
		}

		.bg {
			width: 100%;
			height: 430rpx;
			position: absolute;
			top: 0;
			z-index: -1;
		}

		.borrrow_wrap {
			.borrow_top {
				background: #ffffff;
				border-radius: 10rpx;

				.small_chinese {
					color: #666666;
					font-weight: 500;
					font-family: PingFang SC;

					.small_shu {
						color: #E1E1E1;
					}
				}

				.money_input {
					align-items: baseline;
					color: #333333;
					font-weight: 500;

					.money_sign {
						color: #333333;
						font-weight: bold;
						font-family: PingFang SC;
					}

					.all_btn {
						color: #757575;
					}
				}

				.term_input {
					justify-content: flex-end;

					.default {
						color: #a59d9d;
					}
				}

				.interest_box {
					line-height: 90rpx;

					.interest_desc {
						color: #a2a2a2;
					}

					.interest_right {
						color: #333333;
						font-weight: 500;
						font-family: PingFang SC;
					}
				}
			}

			.credit_certificates {
				border-radius: 10rpx;
				background: linear-gradient(187deg, #FCE8D1, #F8F3ED);

				.title {
					color: #C37133;
					font-weight: bold;
					font-family: PingFang SC;
				}

				.money {
					color: #F05009;
					font-weight: bold;
					font-family: PingFang SC;
				}

				.note {
					color: #C37133;
					font-weight: 500;
					font-family: PingFang SC;
				}
			}

			.repayment_plan {
				border-radius: 10rpx;
				background: #FFFFFF;

				.total_wrap {
					color: #333333;
					line-height: 89rpx;
					border-bottom: 1rpx solid #EDEDED;

					.total_left {
						font-weight: 500;
						font-family: PingFang SC;
					}

					.total_right {
						font-weight: bold;
						font-family: PingFang SC;
					}
				}

				.repayment_wrap {
					@extend .total_wrap;
					border-bottom: none;

					.repayment_left {
						@extend.total_left;
					}

					.repayment_right {
						font-weight: 500;
						font-family: PingFang SC;
					}
				}
			}

			.bottom {
				border-radius: 10rpx;
				background: #FFFFFF;

				.purpose_input {
					justify-content: flex-end;

					.default {
						color: #a59d9d;
					}

					.add {
						color: #3C51F2;
					}
				}

				.institution_wrap {
					line-height: 92rpx;

					.institution_right {
						color: #333333;
						font-weight: 500;
						font-family: PingFang SC;
					}
				}
			}

			.agreement_wrap {
				font-family: PingFang SC;

				.agreement {
					color: #3C51F2;
				}
			}
		}

		.submit_btn {
			color: #FFFFFF;
			background: #C8CCE7;
			height: 100rpx;
			font-weight: bold;
			font-family: PingFang SC;
		}
	}

	.box_fixed {
		@extend .box;
		overflow: hidden;
		height: 100vh;
	}
</style>